package com.example;

import java.io.IOException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.alibaba.fastjson.JSONArray;
import com.example.entity.Article;
import com.example.utils.JdbcUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/article")
public class ArticleList extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Connection conn = null;
        PreparedStatement ppst = null;
        ResultSet rst = null;
        try {

            // 查询数据库
            conn = JdbcUtils.getConnection();
            String sql = "SELECT * from article ORDER BY author_pk collate 'utf8mb4_zh_0900_as_cs';";
            ppst =conn.prepareStatement(sql);
            
            rst = ppst.executeQuery(sql);
            ArrayList<Article> articles = new ArrayList<Article>();

            while(rst.next()){
                Article article = new Article(rst.getInt(1),rst.getString(2),rst.getString(3),rst.getString(4),rst.getDate(5),rst.getDate(6),rst.getInt(7));
                articles.add(article);
            }

            String jsonString = JSONArray.toJSONString(articles);
            System.out.println(jsonString);
            // 带上 Attribute 转发到jsp
            req.getSession().setAttribute("articles", articles);
            req.getRequestDispatcher("/WEB-INF/jsp/articleList.jsp").forward(req, resp);

            
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                JdbcUtils.release(conn, ppst, rst);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
